/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.commonsdk.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.UnsupportedEncodingException;

/**
 * Created by Mikes at 2019-11-11 15:27
 *
 * 自定义TextWatcher，实现EditText限制指定字节数！注意是字节！字节！字节！
 * 一个中文占3个字节，一个英文占1个字节
 */
public class ByteLimitWatcher implements TextWatcher{
    private @NonNull EditText editText;
    private @Nullable TextWatcher watcher;
    private int byteLength;

    public ByteLimitWatcher(@NonNull EditText editText, @Nullable TextWatcher watcher, int byteLength) {
        this.editText = editText;
        this.watcher = watcher;
        this.byteLength = byteLength > 0 ? byteLength : 0;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        if (watcher != null) {
            watcher.beforeTextChanged(s, start, count, after);
        }
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s != null) {
            String tmp = s.toString();
            try {
                if (count > 0 && byteLength > 0) {
                    int cnt = count;
                    do {
                        tmp = s.toString().substring(0, start + cnt) + s.toString().substring(start + count);
                        byte[] bytes = tmp.getBytes("utf-8");
                        if (bytes.length < byteLength) {
                            break;
                        }
                    } while (cnt-- > 0);

                    if (!tmp.equals(s.toString())) {
                        editText.setText(tmp);
                        editText.setSelection(start + cnt);
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (watcher != null) {
            watcher.onTextChanged(s, start, before, count);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (watcher != null) {
            watcher.afterTextChanged(s);
        }
    }
}
